<!-- 维修记录列表 -->
<template>
	<view class="container">

		<up-sticky bgColor="#fff">
			<view class="subsection">
				<u-subsection :list="label" :current="currentTab" @change="sectionChange" activeColor="#1890ff"
					bgColor="#F3F3F3" inactiveColor="#75838E" fontSize="15px" bold height="72" :animation="true"
					buttonColor="#1890ff"></u-subsection>
			</view>

			<!-- <view class="list-search">
				<u-search placeholder="请输入设备名称/编号" v-model="searchData.deviceName" searchIcon="scan"
					@search="getDataList()" @clickIcon="onScan" :showAction="false" shape="round" height="36"
					bgColor="#fff" placeholderColor="#999" searchIconColor="#252B93" color="#333" />
			</view> -->

			<view class="dropDown">
				<u-dropdown ref="uDropdownRef" @open="this.showGzTime = true " @close="this.showGzTime = false">
					<!-- 部门选择 -->
					<u-dropdown-item :title="departmentTitle">
						<view class="slot-content">
							<view class="up-text-center up-content-color up-m-t-20 up-m-b-20">
								<view class="u-page__tag-item" v-for="(dept, index) in departments" :key="index">
									<u-tag :text="dept.label" :plain="!dept.checked" type="primary" :name="index"
										@click="toggleDepartment(index)">
									</u-tag>
								</view>
							</view>
						</view>
					</u-dropdown-item>

					<!-- 属性选择 -->
					<u-dropdown-item :title="attributeTitle">
						<view class="slot-content">
							<view class="up-text-center up-content-color up-m-t-20 up-m-b-20">
								<view class="u-page__tag-item" v-for="(item, index) in attributes" :key="index">
									<u-tag :text="item.label" :plain="!item.checked" type="warning" :name="index"
										@click="toggleAttribute(index)">
									</u-tag>
								</view>
							</view>
						</view>
					</u-dropdown-item>

					<!-- 时间选择 -->
					<u-dropdown-item :title="timeTitle" class="timeFont">
						<view class="slot-content">
							<scroll-view scroll-y="true" style="height: 800rpx;">
								<up-calendar :show="showGzTime" mode="range" @confirm="gzConfirm"
									@close="showGzTime = false" :min-date="minDate" :max-date="maxDate" :monthNum="13"
									:maxRange="10" :rangePrompt="promptMessage"></up-calendar>
							</scroll-view>
						</view>
					</u-dropdown-item>
				</u-dropdown>
			</view>
		</up-sticky>

		<view>
			<u-empty v-if="filteredRecords.length === 0" mode="search">
			</u-empty>
		</view>

		<!-- 维修记录列表 -->
		<view class="task-list">
			<up-list @scrolltolower="scrolltolower" enableFlex>
				<up-list-item class="task-item" v-for="(record, index) in filteredRecords" :key="index">
					<view class="task-info" @click="goToDetail(record.id, record.gzdh,record.whichworhshop)">
						<u-row justify="space-between">
							<u-col span="12">
								<view class="card-title">
									<!-- <text>{{ record.sbbh }}</text> -->
									<text>{{ record.sbmc || "暂无数据" }}</text>
								</view>
							</u-col>
						</u-row>

						<u-row>
							<u-col span="12">
								<view class="card-value">
									<text>设备编号:{{ record.sbbh|| " " }}</text>
								</view>
							</u-col>
						</u-row>

						<u-row>
							<u-col span="12">
								<view class="card-value">
									<text>维修单号:{{ record.ldbh|| " " }}</text>
								</view>
							</u-col>
						</u-row>

						<u-row>
							<u-col span="12">
								<view class="card-value">
									<text>设备区域:{{ record.whichworhshop|| " " }}</text>
								</view>
							</u-col>
						</u-row>

						<u-row>
							<u-col span="12">
								<view class="card-value">
									<text>故障时间:{{ record.faultdate }} {{record.faulttime}}</text>
								</view>
							</u-col>
						</u-row>
					</view>

					<view class="card-tag">
						<u-tag :text=getStatusText(record) plain size="medium" :type="getType(record)"></u-tag>
					</view>
				</up-list-item>
			</up-list>
		</view>

		<view class="u-float-button-con">
			<u-float-button class="u-float-button" :isMenu="false" bottom="160rpx" @click="getToAdd">
			</u-float-button>
		</view>

	</view>

</template>

<script>
	export default {
		data() {
			return {
				searchData: {
					deviceName: '',
					status: '',
					dept: '',
					abc: '',
					starttime: '',
					endtime: '',
				},
				pagination: {
					pageNum: 1, // 当前页码
					pageSize: 20, // 每页条数
					total: 0, // 总条数
				},
				label: ['全部', '待确认', '待审核', '已完成'],
				currentTab: 0,
				filteredRecords: [],
				minDate: "",
				maxDate: "",
				promptMessage: "最多选择5天日期！",
				showGzTime: false,
				departmentTitle: '部门',
				timeTitle: '故障日期',
				attributeTitle: '设备类级',
				departments: [],
				attributes: [],

				// 存储筛选条件
				selectedDepartments: [],
				selectedAttributes: [],
				selectedTime: "",
			};
		},

		mounted() {

		},
		onLoad() {
			this.getDataList();
			this.getDeptList();
			this.getabcList();
			this.initDate();
		},
		onShow() {
			this.filteredRecords = []
			this.pagination.pageNum = 1
			this.getDataList();
		},
		methods: {

			async getDataList() {
				const currentParams = {
					deviceName: this.searchData.deviceName,
					status: this.searchData.status,
					dept: this.searchData.dept,
					abc: this.searchData.abc,
					starttime: this.searchData.starttime,
					endtime: this.searchData.endtime,
				}

				// 如果搜索条件变化，重置分页
				if (JSON.stringify(currentParams) !== JSON.stringify(this.searchParams)) {
					this.pagination.pageNum = 1;
					// this.filteredRecords = [];
					this.searchParams = {
						...currentParams
					}; // 更新搜索条件
				}
				const params = {
					...currentParams,
					pageNum: this.pagination.pageNum,
					pageSize: this.pagination.pageSize
				};
				this.$commonUnits.postRequest(
					"deviceFaultRecord.deviceFaultRepair.getFaultRepairList.mobile",
					params
				).then(res => {
					if (!res.result || res.result.length === 0) {
						if (this.pagination.pageNum === 1) {
							this.filteredRecords = []; // 第一页无数据时清空
						}
						uni.showToast({
							title: '暂无数据',
							icon: 'none'
						});
					} else {
						const newData = res.result.list;
						this.pagination.total = res.result.total;
						if (this.pagination.pageNum === 1) {
							this.filteredRecords = newData;
						} else {
							this.filteredRecords = [...this.filteredRecords, ...newData];
						}

					}
				}).catch(err => {
					this.filteredRecords = [];
					uni.showToast({
						title: '加载失败，请重试',
						icon: 'none'
					});
					console.error('加载故障记录失败:', error);
					// 重置页码
					if (this.pagination.pageNum > 1) {
						this.pagination.pageNum--;
					}
				});
			},

			// 滚动加载更多
			scrolltolower() {
				// 如果已经加载完所有数据，不再请求
				if (this.filteredRecords.length >= this.pagination.total) {
					uni.showToast({
						title: '没有更多数据了',
						icon: 'none'
					});
					return;
				}
				this.pagination.pageNum++;
				this.getDataList();
			},

			// 状态切换
			sectionChange(e) {
				this.currentTab = e;
				this.searchData.status = e
				this.pagination.pageNum = 1
				this.getDataList();
			},

			getDeptList() {
				this.$commonUnits.postRequest(
					"deviceFaultRecord.deviceFaultRepair.getDept.mobile",
				).then(res => {
					if (!res.result || res.result.length === 0) {
						this.departments = [];
						uni.showToast({
							title: '暂无数据',
							icon: 'none'
						});
					} else {
						const filteredResult = res.result.filter(item => item !== null && item.bmmc !== null);
						this.departments = filteredResult.map(item => ({
							label: item.bmmc,
							checked: false
						}));
					}

				}).catch(err => {
					this.departments = [];
				});
			},

			getabcList() {
				this.$commonUnits.postRequest(
					"deviceFaultRecord.deviceFaultRepair.getabc.mobile"
				).then(res => {
					if (!res.result || res.result.length === 0) {
						this.attributes = [];
						uni.showToast({
							title: '暂无数据',
							icon: 'none'
						});
					} else {
						const filteredResult = res.result.filter(item => item !== null && item.abc !== null);
						this.attributes = filteredResult.map(item => ({
							label: item.abc,
							checked: false
						}));
					}
				}).catch(err => {
					this.attributes = [];
				});
			},

			getToAdd() {
				const url = `/pagesOne/pages/repair/faultInfo?mode=add`; //维修填报
				uni.navigateTo({
					url
				});
			},
			// 跳转到详情页
			goToDetail(id, ldbh, whichworhshop) {
				// const url = status === '0' ?
				// 	`/pagesOne/pages/repair/faultInfo?id=${id}` : //维修填报
				// 	`/pagesOne/pages/repair/faultFill?id=${id}`; //维修信息
				const url =
					`/pagesOne/pages/repair/faultInfo?mode=details&id=${id}&ldbh=${ldbh}&sbcq=${whichworhshop}`; //维修填报
				uni.navigateTo({
					url
				});
			},

			toggleDepartment(index) {
				this.departments[index].checked = !this.departments[index].checked;
				const selected = this.departments.filter(dept => dept.checked).map(dept => dept.label);
				this.departmentTitle = selected.length > 2 ? `${selected.slice(0, 2).join(', ')}, ...` :
					selected.length > 0 ? selected.join(', ') : '部门';
				this.searchData.dept = selected.map(item => `'${item}'`).join(', ');
				this.pagination.pageNum = 1; // 重置页码
				this.getDataList();
			},

			toggleAttribute(index) {
				this.attributes[index].checked = !this.attributes[index].checked;
				const selected = this.attributes.filter(attr => attr.checked).map(attr => attr.label);
				this.attributeTitle = selected.length > 2 ? `${selected.slice(0, 2).join(', ')}, ...` :
					selected.length > 0 ? selected.join(', ') : '属性';
				this.searchData.abc = selected.map(item => `'${item}'`).join(', ');
				this.pagination.pageNum = 1; // 重置页码
				this.getDataList();
			},

			gzConfirm(e) {
				if (Array.isArray(e) && e.length >= 1) {
					//传递的Array数组格式["2025-01-01","2025-01-02","2025-01-03"]
					const startDate = e[0]; //开始时间
					const endDate = e[e.length - 1]; //结束时间
					this.timeTitle = `${startDate} 至 ${endDate}`;
					this.searchData.starttime = startDate;
					this.searchData.endtime = endDate;

					// 关闭下拉菜单
					this.$refs.uDropdownRef.close();
					this.showGzTime = false;
					this.getDataList();
				}
			},
			onScan() {
				uni.scanCode({
					success: (res) => {
						this.setData({
							"searchData": res.result
						})
					}
				});
			},

			initDate() {
				let date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
				if (month < 10) {
					month = "0" + month;
				}
				if (day < 10) {
					day = "0" + day;
				}
				let minyear = year - 1;
				this.minDate = minyear + "-" + month + "-" + day;
				this.maxDate = year + "-" + month + "-" + day; //  最大日期可选到今天
				//this.maxDate = year + 1  + '-'+ month +'-' + day; // 最大日期可选到一年后
			},


			getStatusText(item) {
				switch (item.status) {
					case '1':
						return '待确认';
					case '2':
						return '待审核';
					case '3':
						return '已完成';
					default:
						return '待确认';
				}
			},

			getType(item) {
				switch (item.status) {
					case '1':
						return 'primary';
					case '2':
						return 'info';
					case '3':
						return 'success';
					default:
						return 'primary';
				}
			},
		},
	};
</script>

<style lang='scss' scoped>
	.container {
		min-height: 100vh;
		background: #f5f7fa;
	}

	.list-search {
		padding-top: 10px;
		background-color: #fff;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		transition: all 0.3s ease;

		&:active {
			transform: translateY(2rpx);
		}

		:deep(.u-search__content) {
			border-radius: 50rpx !important;
			border: 2rpx solid #1890ff !important;
			box-shadow: 0 2rpx 8rpx rgba(37, 43, 147, 0.1);
			border: 1rpx solid #eee;

			&:focus-within {
				border-color: #1890ff !important;
				box-shadow: 0 2rpx 12rpx rgba(37, 43, 147, 0.2);
			}
		}

		:deep(.u-search__content__input) {
			font-size: 14px;
			padding-left: 20rpx;
		}

		:deep(.u-icon__icon) {
			font-size: 18px !important;
		}
	}

	/* 任务列表样式 */
	.task-list {
		padding: 20rpx;
		z-index: 9999;
	}

	.task-item {
		background: #ffffff;
		border-radius: 12rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.slot-content {
		background-color: #ffffff;
		padding: 24rpx;
	}

	.u-page__tag-item {
		margin-right: 20px;
		display: inline-block;
	}
</style>